package cn.kgc.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * 保证一个线程只有一个Connection
 */
@Component("connectionUtil")
public class ConnectionUtil {
    //本地线程变量
    private ThreadLocal<Connection> threadLocal=new ThreadLocal<Connection>();

    //定义数据源
    @Autowired
    private DataSource dataSource;

    /**
     * 获取Connection对象
     * @return
     * @throws SQLException
     */
    public Connection getConnectin() throws SQLException {
        Connection connection=threadLocal.get();
        if(connection==null){
            connection=dataSource.getConnection();
            threadLocal.set(connection);
        }
        return  connection;
    }

    /**
     * 让当前线程和Connection解绑
     */
    public void removeConnection(){
        threadLocal.remove();
    }




}